# -*- coding: utf-8 -*-
import json
import time
import datetime

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

from submodule.utils.data_center_log import send_log


class CheckMiddleware(MiddlewareMixin):

    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):

        now = datetime.datetime.now()
        t1 = time.time()

        response = self.get_response(request)

        t2 = time.time()
        latency = round((t2 - t1) * 1000, 3)
        req_dict = dict(**request.POST.dict())
        if request.content_type == 'application/json':
            req_dict = json.loads(request.body.decode())
        req_json = json.dumps(req_dict, ensure_ascii=False)
        status_code = response.status_code
        if status_code in [422, 405]:
            status_code = 101
            response = HttpResponse('{"code":"101"}', content_type="application/json")

        # send log
        # content = response.content.decode()
        url_path = request.path
        if url_path != '/':
            api_path = request.build_absolute_uri()
            real_ip = request.META.get('REAL_IP_HEADER')
            tid = request.META.get('HTTP_TID')
            if not real_ip:
                real_ip = request.META.get('REMOTE_ADDR')
            log_data = {
                "clientIp": real_ip,  # 客户端IP
                "apiPath": api_path,  # 请求PATH
                "requestTime": now.strftime('%Y-%m-%d %H:%M:%S'),  # 请求时间
                "totalLatency": latency,  # 请求延迟
                "request": req_json,  # 请求内容
                "response": '{}', #content,  # 返回数据
                "statusCode": str(status_code),  # 返回状态码
                "tid": tid  # tid
            }
            try:
                send_log(log_data)
            except Exception as e:
                print(e)
        return response
